package cc.booku.owlbox.UserSettingsPage;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import androidx.appcompat.widget.Toolbar;

import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dueeeke.videocontroller.MarqueeTextView;
import com.sunfusheng.marqueeview.MarqueeView;
import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnBindViewListener;
import com.timmy.tdialog.listener.OnViewClickListener;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import cc.booku.owlbox.ArtDesign.SystemUtil;

import cc.booku.owlbox.DataAcquisition.AcquisitionActivity;
import cc.booku.owlbox.FileOperations.FileoOperations;
import cc.booku.owlbox.HomeDirectory.HomeDirectoryActivity;
import cc.booku.owlbox.R;
import cc.booku.owlbox.RsaUtil.Decrypt;
import cc.booku.owlbox.RsaUtil.RsaActivity;
import cc.booku.owlbox.Statistics.ChartActivity;
import cc.booku.owlbox.ThanksDonating.ThanksDonatingActivity;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;

import static java.security.AccessController.getContext;

public class UserActivity extends AppCompatActivity {

    private Toolbar Toolbar;
    private TextView tv_thanksmy, tv_thanksD, tv_acquisition, Tv_microblog, Tv_qqgroup, Tv_dataspecification, Tv_port, Tv_aboutapp, Tv_profile, Tv_update, Tv_rootdir, tv_ip, tv_server;
    // private String DefaultPort = "/storage/emulated/0/OwlDatabase/DefaultPort.txt";
    //private String Txt_Profile = "/storage/emulated/0/OwlDatabase/Profile.txt";
    private String ProfilePath = Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator + "Profile.txt";
    private MarqueeView tv_thanksdonating;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);
        //控件触发
        ControlsTrigger();
        //加载标题栏
        LoadToolbar();
        //状态栏颜色
        SystemUtil.setStatusBarColor(this, Color.parseColor("#448aca"));


//        String ProfileStr = FileoOperations.readFromSDFile(this, ProfilePath);
//        //读取配置文件信息
//        try {
//
//
//            JSONObject query = JSON.parseObject(ProfileStr);
//            query.put("加密敏感资源", "333333");
//            Log.d("加密敏感资源", query.toJSONString());
//
//        }catch (Exception e) {
//
//            Toast.makeText(UserActivity.this, "更新地址解析错误", Toast.LENGTH_SHORT).show();
////异常处理
//        }


        tv_thanksdonating = (MarqueeView) findViewById(R.id.tv_thanksdonating);
        String BillBoard_V = FileoOperations.readAssetsTxt(UserActivity.this, "TxtData/BillBoard");
        JSONObject objsd = JSONObject.parseObject(BillBoard_V);
        String result1 = objsd.getString("Donating1");
        String result2 = objsd.getString("Donating2");
        String result3 = objsd.getString("Donating3");
        String result4 = objsd.getString("Donating4");
        List<String> messages = new ArrayList<>();
        messages.add(result1);
        messages.add(result2);
        messages.add(result3);
        messages.add(result4);
        //  Tv_label.startWithList(messages);


// 在代码里设置自己的动画
        tv_thanksdonating.startWithList(messages, R.anim.anim_bottom_in, R.anim.anim_top_out);

    }

    private void LoadToolbar() {
        Toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(Toolbar);//利用Toolbar代替ActionBar
        Toolbar.inflateMenu(R.menu.menu_user);
        //设置的点击事件
        Toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到用户设置页面
                finish();
            }
        });
        //添加menu 菜单点击事件
        Toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_pie_chart:

                        Message msg = new Message();
                        msg.what = 9;
                        handler.sendMessage(msg);//用activity中的handler发送消息

//                        Intent intent = new Intent(UserActivity.this, ChartActivity.class);
//                        startActivity(intent);

                        break;
                    case R.id.action_share:
                        Intent textIntent = new Intent(Intent.ACTION_SEND);
                        textIntent.setType("text/plain");
                        textIntent.putExtra(Intent.EXTRA_TEXT, "软件下载地址：" + "https://lanzous.com/b00nltw9a");
                        startActivity(Intent.createChooser(textIntent, "绿色分享，不含推广内容"));
                        break;

                }
                return true;
            }
        });
    }

    @Override
    public boolean onCreatePanelMenu(int featureId, Menu menu) {
        getMenuInflater().inflate(R.menu.menu_user, menu);//toolbar添加menu菜单
        return true;
    }


    public static Boolean checkUrl(String address, int waitMilliSecond) {
        try {
            URL url = new URL(address);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            conn.setConnectTimeout(waitMilliSecond);
            conn.setReadTimeout(waitMilliSecond);

            //HTTP connect
            try {
                conn.connect();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }

            int code = conn.getResponseCode();
            if ((code >= 100) && (code < 400)) {
                return true;
            }

            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case 9:
                    String ProfileStr = FileoOperations.readAssetsTxt(UserActivity.this, "TxtData/OwlReport");
                    //读取配置文件信息

                    JSONObject obj = JSONObject.parseObject(ProfileStr);
                    String testfile = obj.getString("测试地址");
                    String ciphertext = obj.getString("地址密文");
                    String res = Decrypt.RsaDecrypt(UserActivity.this, ciphertext);


                    HttpResponse(res + testfile, UserActivity.this);


//                    if(!checkUrl(res+testfile,400)){
//                        //请求，将数据写入
//                     //   if (result.equals("yes")) {
////                Log.d("serverTest", res+testfile);
//////                        if (NetPingManager.ping(res)) {
//////                            Log.d("serverTest", "serverTest----" + "服务器在线");
//////                        } else {
//////                            ServerStatusDialog();
//////                        }
//                        HttpResponse(res+testfile,null);
//                            ServerStatusDialog();
//
//
//                        } else {
//                            Log.d("serverTest", "serverTest----" + "连接成功");
//                            Intent intent = new Intent(UserActivity.this, ChartActivity.class);
//                            startActivity(intent);
//                            //Toast.makeText(MainActivity.this, "不检测服务器状态1", Toast.LENGTH_SHORT).show();
//                        }

                    // HttpResponse(res+testfile,UserActivity.this);
//                    if (ping(res)) {
//                        Log.d("serverTest", "serverTest----" + "服务器在线");
//                        Intent intent = new Intent(UserActivity.this, ChartActivity.class);
//                        startActivity(intent);
//                    } else {
//                        ServerStatusDialog();
//                    }


//                    NetPingManager netPingManager = new NetPingManager(UserActivity.this, res, new NetPingManager.IOnNetPingListener() {
//                        @Override
//                        public void ontDelay(long log) {
//                            //todo 延迟ms
//                            Intent intent = new Intent(UserActivity.this, ChartActivity.class);
//                            startActivity(intent);
//
//                        }
//
//                        @Override
//                        public void onError() {
//                            //错误，网络不通
//                            ServerStatusDialog();
//                        }
//                    });
//                    netPingManager.startGetDelay();

                    break;
                case 14:
                    Intent intent = new Intent(UserActivity.this, ChartActivity.class);
                    startActivity(intent);

                    break;


            }
        }
    };


    private void HttpResponse(String url, Context context) {


        OkHttpClient client = new OkHttpClient();
        Request request = new Request
                .Builder()
                .url(url)//要访问的链接
                .build();

        Call call = client.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                String res = response.body().string();
                //Log.i("response===========>",res);
                if (res.equals("owl")) {
                    Intent intent = new Intent(context, ChartActivity.class);
                    startActivity(intent);

//                    Message msg = new Message();
//                    msg.what =14;
//                    handler.sendMessage(msg);//用activity中的handler发送消息


                } else {
                    Log.i("response===========>", res);
                    ServerStatusDialog();
                }

            }
        });

    }

    private void ControlsTrigger() {

        tv_acquisition = (TextView) findViewById(R.id.tv_acquisition);
        tv_acquisition.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(UserActivity.this, AcquisitionActivity.class);
                startActivity(intent);
            }
        });
        tv_server = (TextView) findViewById(R.id.tv_server);
        tv_server.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogServer();

            }
        });


        //关注新浪微博
        Tv_microblog = (TextView) findViewById(R.id.tv_microblog);
        Tv_microblog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    openUserInfoByUid(UserActivity.this, "7455703884");
                } catch (Exception e) {
                    //异常处理
                    Tv_microblog.setText("打开失败！点击重试~");
                }

            }
        });

        //加入qq群聊
        Tv_qqgroup = (TextView) findViewById(R.id.tv_qqgroup);
        Tv_qqgroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    SystemUtil.joinQQGroup(UserActivity.this, "WZXjv7I736JKIJ48YTlIfCuLvHlWTx0a");
                } catch (Exception e) {
                    //异常处理
                    Tv_qqgroup.setText("打开失败！点击重试~");
                }

            }
        });

        Tv_dataspecification = (TextView) findViewById(R.id.tv_dataspecification);
        Tv_dataspecification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//https://lanzous.com/b00nmr4wj
//                try{
//
//                    Intent intent = new Intent(UserActivity.this, ExplainActivity.class);
//                    //用Bundle携带数据
//                    Bundle bundle = new Bundle();
//                    //传递name参数为tinyphp
//                    bundle.putString("interlinkage", "https://lanzous.com/b00nmr4wj");
//                    intent.putExtras(bundle);
//                    startActivity(intent);
//
//                }catch(Exception e){
//                    //异常处理
//                    Tv_qqgroup.setText("打开失败！点击重试~");
//                }

                Uri uri = Uri.parse("https://lanzous.com/b00nmr4wj");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);


            }
        });

        Tv_profile = (TextView) findViewById(R.id.tv_profile);
        //解析口显示在txtview上
        //Tv_port.setText("当前解析口："+FileoOperations.readFromSDFile(this, DefaultPort));
        Tv_profile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UserActivity.this, SettingActivity.class);
                startActivity(intent);


            }
        });

//
//        Tv_port= (TextView)findViewById(R.id.tv_port);
//        //解析口显示在txtview上
//        Tv_port.setText("解析口"+FileoOperations.readFromSDFile(this, DefaultPort));
//        Tv_port.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //点击显示弹窗用于修改
//
//                DialogM3u8();
//
//
//
//            }
//        });


        tv_thanksmy = (TextView) findViewById(R.id.tv_thanksmy);
        tv_thanksmy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //弹窗二维码
                QrcodeBannerDialog("https://qr.alipay.com/fkx00671y2pxjvug8rdup1b");


            }
        });


        tv_thanksD = (TextView) findViewById(R.id.tv_thanksD);
        tv_thanksD.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击显示弹窗用于修改

                // Dialogaboutsoft("当前软件版本：" + packageName(UserActivity.this));
                Intent intent = new Intent(UserActivity.this, ThanksDonatingActivity.class);
                startActivity(intent);


            }
        });

        Tv_aboutapp = (TextView) findViewById(R.id.tv_aboutapp);
        Tv_aboutapp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击显示弹窗用于修改

                Dialogaboutsoft("当前软件版本：" + packageName(UserActivity.this));


            }
        });


        Tv_update = (TextView) findViewById(R.id.tv_update);
        Tv_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击显示弹窗用于修改
                try {

                    Intent intent = new Intent(UserActivity.this, ExplainActivity.class);
                    //用Bundle携带数据
                    Bundle bundle = new Bundle();
                    //传递name参数为tinyphp
                    bundle.putString("interlinkage", "file:////android_asset/app_updatainfo.html");

                    intent.putExtras(bundle);
                    startActivity(intent);

                } catch (Exception e) {
                    //异常处理
                    Tv_qqgroup.setText("打开失败！点击重试~");
                }


            }
        });

        Tv_rootdir = (TextView) findViewById(R.id.tv_rootdir);
        Tv_rootdir.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(UserActivity.this, HomeDirectoryActivity.class);
                startActivity(intent);
            }
        });


        //信息加密
        tv_ip = (TextView) findViewById(R.id.tv_ip);
        tv_ip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(UserActivity.this, RsaActivity.class);
                startActivity(intent);

            }
        });

    }


    public static String packageName(Context context) {
        PackageManager manager = context.getPackageManager();
        String name = null;
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            name = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return name;
    }


    private void QrcodeBannerDialog(final String qrurl) {
        new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.tdialog_qrcode_ad)
                .setScreenHeightAspect(this, 1.0f)
                .setScreenWidthAspect(this, 1.0f)
                .setOnBindViewListener(new OnBindViewListener() {
                    @Override
                    public void bindView(BindViewHolder viewHolder) {
                        //ImageView iv_icon = (ImageView)getActivity().findViewById(R.id.iv_icon);

                        Bitmap bitmap = null;
                        //可对图片进行修改
                        Bitmap logo = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
                        bitmap = CodeCreator.createQRCode(qrurl, 400, 400, logo);
                        if (bitmap != null) {
                            viewHolder.setImageBitmap(R.id.iv_icon, bitmap);
                            viewHolder.setText(R.id.ic_text, "捐赠时请备注昵称及用途");
                        }
                    }
                })
                .addOnClickListener(R.id.iv_close)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                        tDialog.dismiss();
                    }
                })
                .create()
                .show();
    }


    private void Dialogaboutsoft(final String version) {


        new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.tdialog_about_soft)
                .setScreenWidthAspect(this, 1f)
                .setCancelableOutside(false)
                .setOnBindViewListener(new OnBindViewListener() {   //通过BindViewHolder拿到控件对象,进行修改
                    @Override
                    public void bindView(BindViewHolder bindViewHolder) {
                        bindViewHolder.setText(R.id.tv_version, version);
                    }
                })
                .addOnClickListener(R.id.iv_close)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                        tDialog.dismiss();
                    }
                })
                .create()
                .show();
    }


    private void DialogServer() {

        new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.tdialog_server)
                .setScreenWidthAspect(this, 1.0f)
                .setGravity(Gravity.CENTER)
                .setOnBindViewListener(new OnBindViewListener() {   //通过BindViewHolder拿到控件对象,进行修改
                    @Override
                    public void bindView(BindViewHolder bindViewHolder) {
                        //bindViewHolder.setText(R.id.editText, FileoOperations.readAssetsTxt(UserActivity.this,"TxtData/DefaultPort"));
                    }
                })
                .addOnClickListener(R.id.btn_cancel, R.id.btn_affirm)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {

                        EditText editText = viewHolder.getView(R.id.editText);
                        String content = editText.getText().toString().trim();
                        switch (view.getId()) {
                            case R.id.btn_cancel:

                                tDialog.dismiss();
                                break;
                            case R.id.btn_affirm:
                                SettingProfile("地址密文", content);
                                tDialog.dismiss();
                                break;

                        }


                    }
                })

                .create()
                .show();
    }


    private void SettingProfile(String key, String value) {


        String ProfileStr = FileoOperations.readFromSDFile(this, ProfilePath);
        //读取配置文件信息
        try {


            JSONObject query = JSON.parseObject(ProfileStr);
            query.put(key, value);
            Log.d("修改后完整数据", query.toJSONString());

            //保存到数据文件
            FileoOperations.writeAssignTxt(ProfilePath, query.toJSONString());
            Toast.makeText(UserActivity.this, "设置成功", Toast.LENGTH_SHORT).show();

        } catch (Exception e) {

            Toast.makeText(UserActivity.this, "配置发生错误", Toast.LENGTH_SHORT).show();
//异常处理
        }

    }


    public static void openUserInfoByUid(Activity activity, String uid) {
        if (activity == null) {
            return;
        }
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setData(Uri.parse("sinaweibo://userinfo?uid=" + uid));
        activity.startActivity(intent);
    }

    private void ServerStatusDialog() {
        new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.tdialog_serverstatus)
                .setScreenWidthAspect(this, 0.9f)
                .setCancelableOutside(false)
                .addOnClickListener(R.id.tv_close, R.id.tv_qqgroup)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                        switch (view.getId()) {

                            case R.id.tv_close:
                                tDialog.dismiss();
                                break;
                            case R.id.tv_qqgroup:
                                try {
                                    SystemUtil.joinQQGroup(UserActivity.this, "WZXjv7I736JKIJ48YTlIfCuLvHlWTx0a");
                                } catch (Exception e) {
                                    //异常处理
                                    Log.e("--失败--", "添加失败");
                                }
                                tDialog.dismiss();
                                break;
                        }
                    }
                })
                .create()
                .show();
    }


//mWebView.loadUrl("file:///android_asset/test.html");


}
